"""
This script is used for benchmarking the time takes for different formulations
includes
IP, SIP, IP(M*)
"""
from time import time
from ccfs.fscplex import fscplex

f = open("../output/bench_formulations.txt", 'w')
header =  "%4s %4s" % ('NI', 'NS')
header += "%10s %10s %10s" % ("IP_v", "SIP_v", "IP(M*)_v")
header += "%10s %10s %10s" % ('IP_n', "SIP_n", 'IP(M*)_n')
header += "%10s %10s %10s" % ('IP_t', "SIP_t", 'IP(M*)_t')
header += "\n"
f.write(header)

ni_lo = 10
ni_up = 20
ni_de = 5

ns_lo = 10
ns_up = 20
ns_de = 5

# Loop through NI and NS
for NI in range(ni_lo, ni_up, ni_de):
    for NS in range(ns_lo, ns_up, ns_de):
        fc = fscplex()
        fc.generate_instance(NI, NS, eps=0.2, Ordered=False)
        fc.parameters.read_file('../../param/stofac.prm')

        # Solve by original formulation
        t0 = time()
        fc.solve()
        t1 = time()
        ip_v = fc.solution.get_objective_value()
        ip_n = fc.solution.progress.get_num_nodes_processed()
        ip_t = t1-t0

        # Solve by strenghthened formulation
        fc.strengthen_formulation()
        t0 = time()
        fc.solve()
        t1 = time()
        sip_v = fc.solution.get_objective_value()
        sip_n = fc.solution.progress.get_num_nodes_processed()
        sip_t = t1-t0

        # Sovle by big-m coefficients
        x_val = fc.solution.get_values(fc.x_name)
        y_val = fc.solution.get_values(fc.y_name)
        bigm_val = [0] * fc.num_bigm
        for s in fc.S:

            for i in fc.I:
                ind = i + s*fc.NI
                if y_val[s] == 1.0:
                    bigm_val[ind] = max(0, fc.rhs[s][i] - x_val[i] + 0.01)
                else:
                    bigm_val[ind] = 0.01

        fc.set_bigm(bigm_val)
        t0 = time()
        fc.solve()
        t1 = time()
        ipm_v = fc.solution.get_objective_value()
        ipm_n = fc.solution.progress.get_num_nodes_processed()
        ipm_t = t1-t0

        # Print the results 
        line =  "%4d %4d  " % (NI, NS)
        line += "%10f %10f %10f" % (ip_v, sip_v, ipm_v)
        line += "%10d %10d %10d" % (ip_n, sip_n, ipm_n)
        line += "%10f %10f %10f" % (ip_t, sip_t, ipm_t)
        line += "\n"
        f.write(line)
        fc = []

f.close()
